<?php

namespace app\common;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class Token
{
    private static $key = 'EClzMvmBYp5mGc8LNayBut8W5wOwALlgYX6B';
    private static $alg = 'HS256';


    public static function createToken($data, $expiration = 3600*24*30)
    {

        $payload = [
            'iss'  => 'localhost',
            'sub'  => 'token',
            'iat'  => time(),
            'exp'  => time() + $expiration,
            'data' => $data,
        ];

        return JWT::encode($payload, self::$key, self::$alg);

    }

    public static function decodeToken($token)
    {

        try {
            $decoded = JWT::decode($token, new Key(self::$key, self::$alg)); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $res['code']=1;
            $res['data']=$arr['data'];
            return $res;

        } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            $status['msg']="签名不正确";
            $status['code']=0;
            return $status;
        }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg']="token失效";
            $status['code']=0;
            return $status;
        }catch(\Firebase\JWT\ExpiredException $e) { // token过期
            $status['msg']="token失效";
            $status['code']=0;
            return $status;
        }catch(\Exception $e) { //其他错误
            $status['msg']="未知错误";
            $status['code']=0;
            return $status;
        }



    }

    public static function getDataByToken($token)
    {

        $decoded = self::decodeToken($token);

        if (isset($decoded->data)) {
            return $decoded->data;
        } else {
            return false;
        }

    }

    public static function verifyToken($token)
    {

        $result = false;
        if($token == '') return false;
        try {
            return self::decodeToken($token);

        } catch (Exception $e) {

            // Invalid token

        }

        return $result;

    }

}
